<?php
namespace Realisation\Web\Controller;

use Symfony\Component\HttpFoundation\Request;
use Realisation\DataProvider\ApiDataProvider;
use Silex\Application;

/**
 * Description of MessageController
 *
 * @author pahhan
 */
class MessageController extends AbstractApiController
{
    public function get(Request $request, Application $app)
    {
        $url_id = (int) $request->get('url');

        if( !$url_id ) {
            throw new \Exception('Undefined or wrong url value');
        }

        $from_id = (int) $request->get('id');
        $limit = (int) $request->get('limit', 100);
        $provider = new ApiDataProvider($app['db']);
        $stmt = $provider->getMessages($url_id, $from_id, $limit);

        $builder = $this->createBuilder($request);

        $content = $builder->buildMessages($stmt);
        $response = $this->createResponse($request);
        $response->setContent($content);
        return $response;
    }

    public function getCount(Request $request, Application $app)
    {
        $url_id = (int) $request->get('url');

        if( !$url_id ) {
            throw new \Exception('Undefined or wrong url value');
        }

        $from_id = (int) $request->get('id');
        $provider = new ApiDataProvider($app['db']);
        $stmt = $provider->getMessagesCount($url_id, $from_id);

        $builder = $this->createBuilder($request);

        $content = $builder->buildMessagesCount($stmt);
        $response = $this->createResponse($request);
        $response->setContent($content);
        return $response;
    }

}
